import path from "path";
import fse from "fs-extra";
import { formatNow } from "../utils";
import { DIST_FOLDER_NAME } from "../config/const";

const rmLogs = (accessPath: string) => {
  const distFolder = path.join(accessPath, DIST_FOLDER_NAME);
  fse.ensureDirSync(distFolder);

  // 读取日志文件
  const fileNames = fse.readdirSync(distFolder);
  fileNames.forEach((fileName) => {
    try {
      // fileName 格式 '2020-09-02.log'
      const dateStr = fileName.split(".")[0];
      const d = new Date(dateStr);
      const t = Date.now() - d.getTime(); // 获取日志日期，和当前的时间间隔，单位 ms
      if (t / 1000 / 60 / 60 / 24 > 90) {
        // 时间间隔，大于 90 天，则删除日志文件
        const filePath = path.join(distFolder, fileName);
        fse.removeSync(filePath);
      }
    } catch (ex) {
      console.error(`日志文件格式错误 ${fileName}`, ex);
    }
  });
};

export default rmLogs;
